package com.edu.web.load;

import com.edu.entity.resource.Resource;
import com.edu.entity.resource.ResourceTip;
import com.edu.service.load.LoadService;

import com.edu.service.load.TipService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

@Controller
public class LoadController {
    @Autowired
    private LoadService loadService;
    @Autowired
    private TipService tipService;
    @RequestMapping("/upload")
    public String upload(){
        return "load/upload";
    }
    //文件上传相关代码
    @RequestMapping("/upfile")
    public String uploading(HttpServletRequest request) throws IOException {
        String resourceName=request.getParameter("resourceName");
        String resourceType=request.getParameter("resourceType");
//        User user=(User) session.getAttribute("user");
        String resourcePrimary=request.getParameter("resourcePrimary");
        int resourcePrice= Integer.valueOf(request.getParameter("resourcePrice"));
        String resourceTag=request.getParameter("resourceTag");
        String resourceDesc=request.getParameter("resourceDesc");
        System.out.println(resourceName);
        String attachment="";
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request))
        {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
            //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();
            while(iter.hasNext())
            {
                //一次遍历所有文件
                MultipartFile file=multiRequest.getFile(iter.next().toString());
                if(file!=null)
                {
                    String filename=file.getOriginalFilename();
                    String suffix = filename.substring(filename.lastIndexOf(".") + 1);
                    attachment= UUID.randomUUID().toString() +"."+suffix;
                    //获取文件名
                    String filePath = "E:/test/";
                    //自定义上传路径
                    File files = new File(filePath,attachment);
                    if(!files.exists()){//判断文件夹是否存在，如果不存在则创建
                        if(!files.getParentFile().exists()){
                            files.getParentFile().mkdirs();
                        }
                        files.createNewFile();
                    }
                    file.transferTo(files);//上传文件
                }
            }
        }
        Date date = new Date();
        Resource resource = new Resource(resourcePrice,resourceName,"E:/test/"+attachment,resourceTag,resourceType,resourcePrimary,resourceDesc);
        resource.setUploadTime(date);
        loadService.insertfile(resource);
        System.out.println(resource);
        return "redirect:loadhome";
    }


//    @RequestMapping("/loadhome")
//    public String loadhome(Model model,Integer page,Integer size){
//        if (page==null||page==0) {
//            page = 1;
//        }
//        Integer count=loadService.gettotal();
//        List<Resource> list=loadService.findlist(page,size);
//        model.addAttribute("resourcelist",list);
//        model.addAttribute("count",count);
//        model.addAttribute("curr",page);
//        return "load/loadhome";
//    }

    @RequestMapping("/resourcedetail")
    public String resourcedetail(Model model,Integer id,Integer page,Integer size,String resourceName){
        Resource resource=loadService.findById(id);
        model.addAttribute("resource",resource);
        if (page==null||page==0) {
            page = 1;
        }
        Integer count=loadService.gettotal(resourceName);
        List<Resource> relationlist=loadService.findlist(page,size);
        model.addAttribute("relationlist",relationlist);
        model.addAttribute("count",count);
        model.addAttribute("curr",page);
        return "load/detail";
    }

    @RequestMapping("/resourceByName")
    public String resourceByName(Model model,String resourceName,Integer page,Integer size){
        if (page==null||page==0) {
            page = 1;
        }
        if(resourceName == null){
            resourceName = "";
        }
        Integer count=loadService.gettotal(resourceName);
        List<Resource> list=loadService.findByName(resourceName,page,size);
        System.out.println(list);
        model.addAttribute("count",count);
        model.addAttribute("curr",page);
        model.addAttribute("resourcelist",list);
        model.addAttribute("resourceName",resourceName);
        return "load/loadhome";
    }


    //文件下载相关代码
    @RequestMapping("/download")
    public String downloadFile(org.apache.catalina.servlet4preview.http.HttpServletRequest request, HttpServletResponse response){
        String attachment=request.getParameter("attachment");
        String fileName = attachment;
        if (fileName != null) {
            //当前是从该工程的WEB-INF//File//下获取文件(该目录可以在下面一行代码配置)然后下载到C:\\users\\downloads即本机的默认下载的目录
            String realPath = request.getServletContext().getRealPath(
                    "E://test//");
            File file = new File(realPath, fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition",
                        "attachment;fileName=" +  fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("success");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        System.out.println("一个"+fileName);
        return null;
    }

    @RequestMapping("/newtip")
    public String newtip(ResourceTip resourcetip){
        tipService.inserttip(resourcetip);
        return "redirect:loadhome";
    }
}
